package cn.school.classManage.service.impl;

import cn.school.classManage.dao.ClassCurriculumDetailDao;
import cn.school.classManage.dao.ClassCurriculumMainDao;
import cn.school.classManage.dao.ClassCurriculumUserMapper;
import cn.school.classManage.entity.ClassCurriculumDetail;
import cn.school.classManage.entity.ClassCurriculumMain;
import cn.school.classManage.entity.ClassCurriculumUser;
import cn.school.classManage.service.ClassCurriculumMainService;
import cn.school.classManage.service.SchoolClassService;
import cn.school.classManage.vo.*;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.SysUserUtils;
import cn.school.educational.entity.Subject;
import cn.school.educational.service.SubjectService;
import cn.school.sys.dao.TermTimeDao;
import cn.school.sys.entity.TermTime;
import cn.school.sys.service.TermTimeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class ClassCurriculumMainServiceImpl extends ServiceImpl<ClassCurriculumMainDao, ClassCurriculumMain> implements ClassCurriculumMainService {

    @Resource
    ClassCurriculumMainDao classCurriculumMainDao;

    @Resource
    ClassCurriculumDetailDao classCurriculumDetailDao;

    @Resource
    ClassCurriculumUserMapper classCurriculumUserMapper;

    @Resource
    SubjectService subjectService;

    @Resource
    SchoolClassService schoolClassService;

    @Resource
    TermTimeDao termTimeDao;

    @Resource
    TermTimeService termTimeService;

    @Override
    public IPage<ClassCurriculumMainVO> findCurriculumPageList(ClassCurriculumMainVO vo) {
        int count = classCurriculumMainDao.findCurriculumCount(vo);
        int startNum=(vo.getPageNum()-1)*vo.getPageSize();
        vo.setPageNum(startNum);
        List<ClassCurriculumMainVO> commentList =  classCurriculumMainDao.findCurriculumList(vo);
        IPage<ClassCurriculumMainVO> page = new Page<>();
        page.setTotal(count);
        page.setRecords(commentList);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addOrUpdateCurriculum(ClassCurriculumMain vo) {
        String username = SysUserUtils.getSysUser().getUsername();
        int num = 0;
        if(StringUtils.isEmpty(vo.getId())){
            vo.setCreateTime(new Date());
            vo.setCreateBy(username);
            num = this.baseMapper.insert(vo);
            List<ClassCurriculumDetail> detailList = vo.getDetailList();
            for (ClassCurriculumDetail classCurriculumDetail : detailList) {
                classCurriculumDetail.setMainId(String.valueOf(vo.getId()));
                classCurriculumDetail.setCreateBy(username);
                classCurriculumDetail.setCreateTime(new Date());
                classCurriculumDetailDao.insert(classCurriculumDetail);
            }
        }else{
            vo.setModifyTime(new Date());
            vo.setModifyBy(username);
            num = this.baseMapper.updateById(vo);
            List<ClassCurriculumDetail> detailList = vo.getDetailList();
            for (ClassCurriculumDetail classCurriculumDetail : detailList) {
                classCurriculumDetail.setMainId(String.valueOf(vo.getId()));
                classCurriculumDetail.setCreateBy(username);
                classCurriculumDetail.setCreateTime(new Date());
                classCurriculumDetailDao.updateById(classCurriculumDetail);
            }
        }
        return num;
    }

    @Override
    public Integer addAllUser(ClassCurriculumMain vo) {
        return null;
    }


    @Override
    public Integer deleteCurriculum(ClassCurriculumMain vo) {
        int num=0;
        if(!StringUtils.isEmpty(vo.getId())){
            num = this.baseMapper.deleteById(vo.getId());
            //删除详情
            LambdaQueryWrapper<ClassCurriculumDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ClassCurriculumDetail::getMainId,String.valueOf(vo.getId()));
            classCurriculumDetailDao.delete(wrapper);
        }
        return num;
    }

    @Override
    public ClassCurriculumMain findDetail(ClassCurriculumMainVO vo) {
        LambdaQueryWrapper<ClassCurriculumMain> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(vo.getId())){
            wrapper.eq(ClassCurriculumMain::getId,vo.getId());
        }
        if(!StringUtils.isEmpty(vo.getClassId())){
            wrapper.eq(ClassCurriculumMain::getClassId,vo.getClassId());
        }
        if(!StringUtils.isEmpty(vo.getTermId())){
            wrapper.eq(ClassCurriculumMain::getTermId,vo.getTermId());
        }
        ClassCurriculumMain main = this.baseMapper.selectOne(wrapper);
        if(main == null){
            main = new ClassCurriculumMain();
            main.setClassId(vo.getClassId());
            main.setTermId(vo.getTermId());
            return main;
        }
        LambdaQueryWrapper<ClassCurriculumDetail> wrapperDetail = new LambdaQueryWrapper<>();
        wrapperDetail.eq(ClassCurriculumDetail::getMainId,main.getId());
        wrapperDetail.orderByAsc(ClassCurriculumDetail::getSessionsId);
        main.setDetailList(classCurriculumDetailDao.selectList(wrapperDetail));
        return main;
    }

    @Override
    public ClassCurriculumMain findDetailss(ClassCurriculumMainVO vo) {
        LambdaQueryWrapper<ClassCurriculumMain> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClassCurriculumMain::getId,vo.getId());
        ClassCurriculumMain main = this.baseMapper.selectById(vo.getId());
        LambdaQueryWrapper<ClassCurriculumUser> wrapperDetail = new LambdaQueryWrapper<>();
        wrapperDetail.eq(ClassCurriculumUser::getMainId,vo.getId());
        wrapperDetail.orderByAsc(ClassCurriculumUser::getSessionsId);
        main.setUserList(classCurriculumUserMapper.selectList(wrapperDetail));
        return main;
    }


    @Override
    public ClassCurriculumMainVO findStudentCurriculumDetail(ClassCurriculumMainVO vo) {
        List<TermTime> termTimeList = termTimeService.getTermTimeByDate();
        Long id = 0L;
        if(termTimeList!=null && termTimeList.size()>0){
            id = termTimeList.get(0).getId();
        }
        if(StringUtils.isEmpty(vo.getClassId()) && StringUtils.isEmpty(vo.getId())){
            throw new ApiException("参数错误");
        }
        if(!StringUtils.isEmpty(vo.getClassId())){
            vo.setTermId(id+"");
        }

        //查询主表信息
        vo.setPageNum(0);
        vo.setPageSize(Integer.MAX_VALUE);
        List<ClassCurriculumMainVO> mainList = classCurriculumMainDao.findCurriculumList(vo);
        ClassCurriculumMainVO mainVO = new ClassCurriculumMainVO();
        if(mainList != null && mainList.size()>0){
            mainVO = mainList.get(0);
        }
        List<ClassCurriculumDetailVO> detailVOList = classCurriculumDetailDao.getDetailListByMainID(mainVO.getId());
        mainVO.setDetailList(detailVOList);
        return mainVO;
    }

    @Override
    public CommonResult importCurriculumExcel(InputStream inputStream) throws IOException {
        //班级列表
        List<SchoolClassVO> classList = schoolClassService.findAllSchoolClass();
        //科目列表
        List<Subject> subjectList = getSubjectList();

        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        //读取第一个sheet
        XSSFSheet sheet = workbook.getSheetAt(0);
        String classId ="";
        String termTimeID = "";
        ClassCurriculumMain mainEntity = new ClassCurriculumMain();
        List<ClassCurriculumDetail> detailList = new ArrayList<>();
        ClassCurriculumDetail detail = null;
        // 3.获取行
        for (int i=1; i<sheet.getPhysicalNumberOfRows();i++) {
            //获取每行的内容
            Row row = sheet.getRow(i);
            //获取到班级和学期
            if(i==1){
                for (int j=0; j<row.getLastCellNum();j++) {
                    Cell cell = row.getCell(j);
                    if(j==1){
                        classId = getClassId(cell.getStringCellValue(),classList);
                        if(StringUtils.isEmpty(classId)) return CommonResult.failed("班级名称不存在，请修改后再导入");
                        mainEntity.setClassId(classId);
                    }
                    if(j==3){
                        termTimeID = getTermTimeId(cell.getStringCellValue());
                        if(StringUtils.isEmpty(termTimeID)) return CommonResult.failed("学期不存在，请修改后再导入");
                        mainEntity.setTermId(termTimeID);
                    }
                }
            }else{
                detail = new ClassCurriculumDetail();
                    if(i>2){
                        for (int j=0; j<row.getLastCellNum();j++) {
                            Cell cell = row.getCell(j);
                            if(j==0){
                                detail.setSessionsId(cell.getStringCellValue());
                            }
                            if(j==1){
                                detail.setMondaySubjectId(getSubjectId(cell.getStringCellValue(),subjectList));
                            }
                            if(j==2){
                                detail.setTuesdaySubjectId(getSubjectId(cell.getStringCellValue(),subjectList));
                            }
                            if(j==3){
                                detail.setWednesdaySubjectId(getSubjectId(cell.getStringCellValue(),subjectList));
                            }
                            if(j==4){
                                detail.setThursdaySubjectId(getSubjectId(cell.getStringCellValue(),subjectList));
                            }
                            if(j==5){
                                detail.setFridaySubjectId(getSubjectId(cell.getStringCellValue(),subjectList));
                            }
                            if(j==6){
                                detail.setSaturdaySubjectId(getSubjectId(cell.getStringCellValue(),subjectList));
                            }
                            if(j==7){
                                detail.setSundaySubjectId(getSubjectId(cell.getStringCellValue(),subjectList));
                            }
                        }
                        detailList.add(detail);
                    }
                }

        }
        mainEntity.setDetailList(detailList);
        int num = this.addOrUpdateCurriculum(mainEntity);
        if(num>0){
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    /**
     * 获取学期ID
     * @param termTime
     * @return
     */
    private String getTermTimeId(String termTime){
        LambdaQueryWrapper<TermTime> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TermTime::getTenantId, SysUserUtils.getSysUser().getTenantId());
        wrapper.eq(TermTime::getRemarks,termTime);
        List<TermTime> list = termTimeDao.selectList(wrapper);
        for (TermTime time : list) {
            if(termTime.equals(time.getRemarks())){
                return time.getId()+"";
            }
        }
        return null;
    }


    /**
     * 获取班级ID
     * @param className
     * @param list
     * @return
     */
    private String getClassId(String className, List<SchoolClassVO> list){
        for (SchoolClassVO vo : list) {
            if(className.equals(vo.getClassName())){
                return vo.getId()+"";
            }
        }
        return null;
    }

    private List<Subject> getSubjectList(){
        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Subject::getTenantId, SysUserUtils.getSysUser().getTenantId());
        return subjectService.getBaseMapper().selectList(wrapper);
    }

    /**
     * 获取科目ID
     * @param subjectName
     * @param list
     * @return
     */
    private String getSubjectId(String subjectName, List<Subject> list){
        if(StringUtils.isEmpty(subjectName)){
            return "";
        }
        for (Subject subject : list) {
            if(subjectName.equals(subject.getSubjName())){
                return subject.getId()+"";
            }
        }
        return null;
    }
}
